<template>
  <div class="sparepartDoc zy-content">
    <div class="wapperConent">
      <Row>
        <Col class="wapperLeft">
          <div>
            <Tree :data="data5" :render="renderContent" ref="tree"></Tree>
          </div>
        </Col>
        <Col class="wapperRight">
          <div class="searchBox search-box-layout">
            <Row :gutter="24">
              <Col span="4">
                <div>
                  <p class="label">{{ $t('doc.KeyWord') }}</p>
                  <div class="ipt">
                    <Input type="text" v-model="fileName" :placeholder="`${$t('common.inputInfo')}`"/>
                  </div>
                </div>
              </Col>
              <Col span="4">
                <div>
                  <p class="label hide-label">--</p>
                  <div class="ipt">
                    <Button class="search-btn" type="primary" v-has="'sparepartDocQuery'" @click="clickSearchBtn">
                      {{ $t('common.Query') }}
                    </Button>
                    <Button
                        class="reset-btn"
                        @click="changeNum()"
                    >{{ $t('common.reset') }}
                    </Button>
                  </div>
                </div>
              </Col>
            </Row>
          </div>
          <div class="list-layout mt16">
            <div class="btns clear">

              <span class="title">{{ $t('common.listInformation') }}</span>
              <Button @click="importPrrShowH" v-has="'sparepartDocUploadFile'">{{ $t('ledger.uploadFiles') }}</Button>
              <Button @click="deleteAll" v-has="'sparepartDocDeleteAll'">{{ $t('common.batchDelete') }}</Button>
            </div>
            <div class="basicData tableContent">
              <Table :columns="columns1" :data="tableList" @on-selection-change="onSelectChange">
                <template slot-scope="{ row }" slot="fileSize">
                            <span v-if="!row.fileSize">
                            </span>
                  <span v-else-if="row.fileSize < 1024">
                              {{ parseFloat(row.fileSize).toFixed(2) + 'B' }}
                            </span>
                  <span v-else-if="row.fileSize < 1024 * 1024">
                              {{ parseFloat(row.fileSize / 1024).toFixed(2) + 'K' }}
                            </span>
                  <span v-else-if="row.fileSize < 1024 * 1024 * 1024">
                              {{ parseFloat(row.fileSize / 1024 / 1024).toFixed(2) + 'M' }}
                            </span>
                  <span v-else-if="row.fileSize < 1024 * 1024 * 1024">
                              {{ parseFloat(row.fileSize / 1024 / 1024 / 1024).toFixed(2) + 'G' }}
                            </span>
                </template>
                <template slot-scope="{ row }" slot="visitCount">
                  <span style="color: #2D8CF0;cursor: pointer" @click="numberShow(row.id,1)">{{
                      row.visitCount || 0
                    }}</span>
                </template>
                <template slot-scope="{ row }" slot="downLoadTimes">
                  <span style="color: #2D8CF0;cursor: pointer" @click="numberShow(row.id,2)">{{
                      row.downLoadTimes || 0
                    }}</span>
                </template>
                <template slot-scope="{ row }" slot="action">
                  <div class="ivu-table-cell-slot">
                    <span class="operationBtn" v-has="'sparepartDocPriview'" @click="viewDocument(row, false)"><i class="iconfont zy-common-yulan"></i>{{ $t('ledger.Preview') }}</span>
                    <!--                          v-show="row.realJudge == 'true'"-->
                    <span class="operationBtn" v-has="'sparepartDocDown'" @click="viewDocument(row, true)"><i class="iconfont zy-common-xiazai"></i>{{ $t('doc.download') }}</span>
                    <span class="operationBtn" v-has="'sparepartDocDelete'" @click="(deleteModalDoc = true, documentIds = [row.id])"><i class="iconfont zy-common-shanchu"></i>{{ $t('common.Delete') }}</span>
                  </div>
                  <!--                          v-show="row.previewJudge == 'true'"-->

                </template>
              </Table>
            </div>
            <div class="pageWrap mt16">
              <pageLeftTitle :total="total" :selected="documentIds.length"/>
              <Page :total="total" :current="pageNum" show-total show-sizer @on-change="changePageNum"
                    @on-page-size-change="changePageSize"/>
            </div>
          </div>
        </Col>
      </Row>

      <!-- 批量导入 -->
      <docImport ref="docImport"
                 :selectTreeId="folderHierarchyId"
                 :attachmentBelongTo="2"
                 @importPrrBtn="importPrrBtnH"
      ></docImport>

      <iframeModalCompent v-if="iframeShow" :isStudy="false" :iframeShow="iframeShow" :iframeModalSrc="iframeModalSrc"
                          @closeIframe="iframeShow = false"></iframeModalCompent>

      <numberModal ref="numberModal"></numberModal>
      <Modal :mask-closable="false" v-model="deleteModal" class="modal-title-layout" :title="$t('common.Delete')">
<!--        <Row class="enableContent">-->
<!--          <Col span="24" class="enableContentInner">-->
<!--            <img width="95px" src="~images/event/del.png" alt=""/>-->
<!--          </Col>-->
<!--          <Col span="24" class="enableTips">-->
<!--            <span>删除后，当前文件夹及其项下文件夹内容及文档全部删除，</span>-->
<!--            <div><span>{{ $t('common.sureDelete') }}</span></div>-->
<!--          </Col>-->
<!--        </Row>-->
        <div class="icon red">
          <i class="iconfont zy-common-shanchu"></i>
        </div>
        <p class="title">
          <span>删除后，当前文件夹及其项下文件夹内容及文档全部删除，<br>{{ $t('common.sureDelete') }}</span>
        </p>
        <div slot="footer">
          <Button type="default" @click="deleteModal = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="deleteFolder">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>
      <Modal :mask-closable="false" v-model="deleteModalDoc" title="">
        <Row class="enableContent">
          <Col span="24" class="enableContentInner">
            <img width="95px" src="~images/event/del.png" alt=""/>
          </Col>
          <Col span="24" class="enableTips">
            <span>删除后无法恢复，请确认是否删除？</span>
          </Col>
        </Row>
        <div slot="footer">
          <Button type="default" @click="deleteModalDoc = false">{{ $t('common.Cancle') }}</Button>
          <Button type="primary" @click="deleteFolderDoc">{{ $t('maintenance.Confirmed') }}</Button>
        </div>
      </Modal>
    </div>
  </div>

</template>

<script>
import qs from 'qs'
// import {Button, Icon, Page, Table, Input} from "iview";
// import {Tree} from 'view-design'
import docImport from "../../knowledgeBase/modal/docImport.vue";
import iframeModalCompent from "../../knowledgeBase/modal/iframe.vue";
import numberModal from "../../knowledgeBase/modal/number.vue";

export default {
  name: "sparepartDoc",
  components: {
    // Button, Icon, Page, Table, Input, Tree,
    docImport,
    iframeModalCompent,
    numberModal
  },
  data() {
    return {
      iframeShow: false, // 预览弹窗
      iframeModalSrc: "",
      deleteModal: false,
      pageSize: 10,
      pageNum: 1,
      total: 0,
      fileName: "",
      tableList: [],
      importPrrShowF: false, //是否显示批量导入弹窗
      columns1: [
        {
          key: "selection",
          type: "selection",
          width: 60,
          align: "center",
        },
        {
          //title: "名称",
          title: `${this.$t('doc.Name')}`,
          key: "fileName",
          align: "left",
          width: 400,
          ellipsis: true,
          tooltip: true
        },
        {
          // title: "类型",
          title: `${this.$t('doc.Type')}`,
          key: "suffix",
          align: "center",
          width: 120,
        },
        {
          //title: "文件大小",
          title: `${this.$t('doc.FileSize')}`,
          slot: "fileSize",
          align: "center",
          width: 120,
        },
        {
          // title: "描述",
          title: `${this.$t('doc.Des')}`,
          key: "fileDescription",
          align: "center ",
          ellipsis: true,
          tooltip: true
        },
        {
          // title: "浏览次数",
          title: `${this.$t('doc.SeenBy')}`,
          align: "center ",
          slot: "visitCount",
          width: 120,
        },
        {
          // title: "下载次数",
          title: `${this.$t('doc.Download')}`,
          align: "center ",
          slot: "downLoadTimes",
          width: 120,
        },
        {
          title: `${this.$t('common.operation')}`,
          slot: "action",
          width: this.util.autoWidth(250,320),
          fixed: "right",
          align: "center",
        }
      ],
      data5: [
        {
          title: "备件资料",
          expand: true,
          id: 0,
          render: (h, {data}) => {
            return h('span', {
              style: {
                display: 'inline-block',
                width: '100%'
              }
            }, [
              h('span', [
                h('Icon', {
                  props: {
                    type: 'ios-folder'
                  },
                  style: {
                    marginRight: '8px',
                    color: '#ffe79b'
                  }
                }),
                h("span", data.title)
              ]),
              h(
                  "span",
                  {
                    style: {
                      display: "inline-block",
                      marginLeft: "32px"
                    }
                  },
                  [
                    h("Button", {
                      props: Object.assign({}, this.buttonProps, {
                        icon: "ios-add",
                      }),
                      style: {
                        marginRight: '8px',
                        width: '20px',
                        height: '20px',
                        marginTop: '-2px'
                      },
                      on: {
                        click: () => {
                          this.append(data);
                        }
                      },
                      directives: [{
                        name: 'has',
                        value: 'sparepartDocAddDoc'
                      }]
                    },)
                  ]
              )


            ]);
          },
          children: []
        }
      ],
      buttonProps: {
        type: "default",
        size: "small"
      },
      // 输入框要修改的内容
      inputContent: "",
      folderId: null, // 删除文件夹id
      folderHierarchyId: null, // 右侧数据所属文件夹id
      deleteModalDoc: false,
      documentIds: [],
      expandObj: {}, // 树的收起和展开
      selectedId: null // 左侧文件夹选中id
    };
  },
  mounted() {
    this.getTreeList(true);
  },
  methods: {
    // 删除左侧文件夹
    deleteFolder() {
      this.axios({
        method: "get",
        url: "/dms/folderHierarchy/delete",
        params: {folderId: this.folderId}
      }).then(res => {
        if (res.code === 200) {
          const root = this.$refs.tree._data.flatState
          // 如果删除的是当前选中的文件夹
          if (this.folderId === this.folderHierarchyId) {
            root.forEach(v => {
              if (v.node.id === this.folderId) {
                this.folderHierarchyId = v.node.parentId
                this.clickSearch()
              }
            })
          }
          this.expandObj = {}
          root.forEach(v => {
            this.expandObj[v.node.id] = v.node.expand
          })
          this.$Message.success('删除成功！')
          this.getTreeList()
          this.deleteModal = false
        }
      });
    },
    // 删除右侧文档
    deleteFolderDoc() {
      this.axios({
        method: "post",
        url: "/dms/documentAttachment/delete",
        data: this.documentIds
      }).then(res => {
        if (res.code === 200) {
          this.$Message.success('删除成功！')
          this.clickSearch()
          this.deleteModalDoc = false
        }
      });
    },
    numberShow(id, state) {
      this.$refs.numberModal.show(id, state)
    },
    // 上传文件
    importPrrShowH() {
      this.$refs.docImport.show()
    },
    importPrrBtnH() {
      //批量导入点击关闭按钮=
      this.pageNum = 1;
      this.clickSearch();
    },

    clickSearchBtn() {
      this.pageNum = 1;
      this.clickSearch();
    },
    clickSearch(folderHierarchyId = this.folderHierarchyId) {
      this.axios({
        method: "post",
        url: "/dms/documentAttachment/list",
        data: {
          folderHierarchyId,
          attachmentBelongTo: 2,
          operationType: 1,
          fileDescription: this.fileName,
          pageNum: this.pageNum,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.code === 200) {
          this.tableList = res.data.list;
          this.total = res.data.total;
        }
      });
    },
    changePageSize(value) {
      this.pageNum = 1;
      this.pageSize = value;
      this.clickSearch();
    },
    changePageNum(value) {
      this.pageNum = value;
      this.clickSearch();
    },
    // 预览和下载
    viewDocument(row, isDown) {
      this.axios({
        method: "post",
        url: "/dms/operationRecord/add",
        data: {
          documentAttachmentId: row.id,
          operationType: isDown ? 2 : 1,
          operationTime: this.$moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
        }
      }).then(res => {
        if (res.code === 200) {
          if (isDown) {
            // window.open(row.fileUrl, "_blank");
            let a = document.createElement('a')
            a.style.display = 'none'
            a.href = this.util.filePathToUrl(row.filePath)
            a.download = row.fileName
            document.body.appendChild(a)
            a.click()
            a.remove()
          } else {
            this.iframeShow = true
            let env = process.env.NODE_ENV;
            let origin = window.location.origin;
            let path = '/kakone';
            if (env === 'tong') {
              path = '';
            }
            let fileUrl = origin + this.util.filePathToUrl(row.filePath);
            console.log(origin);
            this.iframeModalSrc = origin + path + `/fileServer/onlinePreview?url=${fileUrl}`

          }
          this.clickSearch()
        } else {
          this.$Message.warning(({content: res.msg, duration: 6, closable: true}));
        }
      });
    },
    getTreeList(isFirst = false) {
      this.axios({
        method: "get",
        url: "/dms/folderHierarchy/list",
        params: {
          folderBelongTo: 1
        }
      }).then(res => {
        if (res.code === 200) {
          if (res.data[0] && isFirst) {
            this.folderHierarchyId = res.data[0].id
            this.clickSearch()
          }
          this.data5[0].children = this.deepMap(res.data)
        }
      });
    },
    deepMap(arr) {
      return arr.map(v => ({
        title: v.folderName,
        id: v.id,
        expand: this.expandObj[v.id],
        parentId: v.parentId,
        selected: v.id === this.folderHierarchyId,
        children: v.folderHierarchyVos && v.folderHierarchyVos.length ? this.deepMap(v.folderHierarchyVos) : []
      }))
    },
    // 树渲染逻辑
    renderContent(h, {root, node, data}) {
      return h("span", {
        class: "treeBox",
        style: {
          display: 'inline-block',
          width: '100%',
          cursor: 'pointer'
        },
        on: {
          click: () => {
            // 点击Tree节点触发
            data.editState ? '' : this.handleClickTreeNode(data.id)
          }
        }
      }, [
        h('span', [
          h('Icon', {
            props: {
              type: `${'ios-folder'}`
            },
            style: {
              marginRight: '8px',
              color: '#ffe79b'
            }
          }),
          h(`${data.editState ? '' : 'span'}`, {
            style: {
              position: 'relative'
            },
          }, data.title),
          h(`${data.editState ? 'input' : ''}`,
              {
                attrs: {
                  value: `${data.editState ? data.title : ''}`,
                  autofocus: true,
                  placeholder: '请输入'
                },
                style: {
                  width: '120px',
                  cursor: 'auto',
                  border: '1px solid #000000'
                },
                on: {
                  change: (event) => {
                    this.inputContent = event.target.value
                  },
                  keyup: (e) => {
                    // 回车键
                    if (e.keyCode === 13) {
                      if (data.id) { // 编辑
                        this.axios({
                          method: "post",
                          url: "/dms/folderHierarchy/update",
                          data: {
                            folderName: this.inputContent || '请输入',
                            parentId: data.parentId,
                            folderBelongTo: 1,
                            id: data.id,
                          }
                        }).then(res => {
                          if (res.code === 200) {
                            this.expandObj = {}
                            root.forEach(v => {
                              this.expandObj[v.node.id] = v.node.expand
                            })
                            this.$Message.success('编辑成功')
                            this.getTreeList()
                          } else {
                            this.$Message.warning({content: res.msg, duration: 6, closable: true,});
                          }
                        });
                      } else { // 新增
                        this.axios({
                          method: "post",
                          url: "/dms/folderHierarchy/add",
                          data: {
                            folderName: this.inputContent || '请输入',
                            parentId: data.parentId,
                            folderBelongTo: 1
                          }
                        }).then(res => {
                          if (res.code === 200) {
                            this.$Message.success('新增成功')
                            this.expandObj = {}
                            root.forEach(v => {
                              this.expandObj[v.node.id] = v.node.expand
                            })
                            this.getTreeList()
                          } else {
                            this.$Message.warning({content: res.msg, duration: 6, closable: true,});
                          }
                        });
                      }
                    }
                  }
                }
              }
          ),
        ]),
        // 增删改按钮部分
        h('span',
            {
              class: "btnNone",
              style: {marginLeft: '1rem'}
            },
            [
              //操作按钮部分
              // 添加按钮
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-add'
                }),
                style: {
                  marginRight: '8px',
                  width: '20px',
                  height: '20px',
                  marginTop: '-2px'
                },
                on: {
                  click: () => {
                    if (data.id) {
                      this.append(data)
                      if (!data.expand) this.$set(data, 'expand', true)
                    }
                  }
                },
                directives: [{
                  name: 'has',
                  value: 'sparepartDocAddDoc'
                }]
              }),
              // 删除按钮
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-remove'
                }),
                style: {
                  marginRight: '8px',
                  width: '20px',
                  height: '20px',
                  marginTop: '-2px'
                },
                on: {
                  click: () => {
                    if (data.id) {
                      this.deleteModal = true
                      this.folderId = data.id
                    } else {
                      this.filterTreeList(root, node, data)
                    }
                  }
                },
                directives: [{
                  name: 'has',
                  value: 'sparepartDocDeleteDoc'
                }]
              }),
              // 编辑按钮
              h('Button', {
                props: Object.assign({}, this.buttonProps, {
                  icon: 'ios-brush-outline'
                }),
                style: {
                  marginRight: '8px',
                  width: '20px',
                  height: '20px',
                  marginTop: '-2px'
                },
                on: {
                  click: () => {
                    if (data.id) {
                      this.editTree(data)
                    }
                  }
                },
                directives: [{
                  name: 'has',
                  value: 'sparepartDocEditDoc'
                }]
              })
            ]
        ),
        // // 确认/取消修改部分
        // h(`${ data.editState ? 'span' : ''}`,
        //     {
        //         style: {
        //             // position:'absolute',
        //             marginLeft:'.5rem'
        //         }
        //     },
        //     [
        //         // 确认按钮
        //         h('Button', {
        //             props: Object.assign({}, this.buttonProps, {
        //                 icon: 'md-checkmark'
        //             }),
        //             style: {
        //                 // marginRight: '8px',
        //                 border:0,
        //                 background:'rgba(0,0,0,0)',
        //                 fontSize:'1.3rem',
        //                 outline:"none"
        //             },
        //             on: {
        //                 click: (event) => {
        //                     this.confirmTheChange(data)
        //                 }
        //             }
        //         }),
        //         // 取消按钮
        //         h('Button', {
        //             props: Object.assign({}, this.buttonProps, {
        //                 icon: 'md-close'
        //             }),
        //             style: {
        //                 border:'0',
        //                 background:'rgba(0,0,0,0)',
        //                 fontSize:'1.3rem',
        //                 outline:"none"
        //             },
        //             on: {
        //                 click: () => { this.CancelChange(data) }
        //             }
        //         })
        //     ]
        // )
      ]);
    },
    filterTreeList(root, node, data) {
      const parentKey = root.find(el => el === node).parent;
      const parent = root.find(el => el.nodeKey === parentKey).node;
      const index = parent.children.indexOf(data);
      parent.children.splice(index, 1);
    },
    // 控制Tree当前状态函数
    setStates(data) {
      var editState = data.editState;
      if (editState) {
        this.$set(data, "editState", false);
      } else {
        this.$set(data, "editState", true);
      }
    },
    deleteAll() {
      if (this.documentIds.length == 0) {
        this.$Message.warning({
          content: `${this.$t('common.deleteItems')}`,
          duration: 6,
          closable: true,
        });
        return;
      } else {
        this.deleteModalDoc = true;
      }
    },
    onSelectChange(selection) {
      this.documentIds = selection.map((item) => item.id);
    },
    // Tree修改按钮
    editTree(data) {
      event.stopPropagation();
      this.inputContent = data.title;
      this.setStates(data);
    },
    // 添加按钮
    append(data) {
      this.inputContent = ''
      const children = data.children || [];
      children.push({
        title: '',
        expand: true,
        editState: true,
        parentId: data.id
      });
      this.$set(data, 'children', children);
      // this.canUnwindCode = data.code;
      // event.stopPropagation();
      // let add_data = {
      //     title: "新建节点",
      //     parentCode: data.code,
      //     itemSort: data.itemSort
      // };
      // this.$Modal.confirm({
      //     title: "提示",
      //     content: `您确定新增吗？`,
      //     onOk: () => {
      //         this.axios({
      //           headers: {
      //             'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
      //           },
      //             method: "post",
      //             url: "/dms/knowledge/add",
      //             data: qs.stringify(add_data)
      //         }).then(res => {
      //             if (res.code === 200) {
      //                 const children = data.children || [];
      //                 children.push({
      //                     title: "新建节点",
      //                     expand: true
      //                 });
      //                 this.$set(data, "children", children);
      //                 this.getTreeList();
      //             }
      //         });
      //     },
      //     onCancel: () => {
      //         this.$Message.info("取消");
      //     }
      // });
    },
    // 确认修改树节点
    confirmTheChange(data) {
      this.canUnwindCode = data.code;
      this.isfocus = true;
      if (!this.inputContent) {
        this.$Notice.warning({
          title: "当前输入有误"
        });
      } else {
        if (this.inputContent.length > 100) {
          this.$Message.warning("输入长度不能大于100！");
          return false;
        }

        if (this.oldName !== this.inputContent) {
          let eidt_data = {
            id: data.id,
            itemSort: data.itemSort,
            title: this.inputContent
          };
          this.$Modal.confirm({
            title: "提示",
            content: `您确定将  “${this.oldName}”  重命名为 “ ${this.inputContent} ” 吗？`,
            onOk: () => {
              this.axios({
                method: "post",
                url: "/dms/knowledge/update",
                headers: {
                  'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
                },
                data: qs.stringify(eidt_data)
              }).then(res => {
                if (res.code === 200) {
                  data.title = this.inputContent;
                  this.$Message.info("修改成功");
                  this.getTreeList();
                }
              });
            },
            onCancel: () => {
              this.$Message.info("取消");
            }
          });
          this.setStates(data);
        } else {
          this.setStates(data);
        }
      }
    },
    // 取消修改树节点
    CancelChange(data) {
      this.$Notice.info({
        title: "取消修改"
      });
      this.setStates(data);
    },
    // 点击Tree节点触发
    handleClickTreeNode(folderHierarchyId) {
      this.pageNum = 1;
      this.folderHierarchyId = folderHierarchyId
      this.clickSearch();
    }
  }
};
</script>

<style scoped lang="scss">
.sparepartDoc {
  .wapperConent {
    width: 100%;
    padding: 10px 0;

    .wapperLeft {
      width: 20%;
      min-height: 750px;
      max-height: 750px;
      float: left;
      background-color: #ffffff;
      padding: 10px;
      margin-right: 1%;
      border-radius: 5px;
      overflow-y: scroll;
    }

    .wapperLeft::-webkit-scrollbar {
      /*滚动条整体样式*/
      width: 5px; /*高宽分别对应横竖滚动条的尺寸*/
      height: 5px;
    }

    .wapperRight {
      width: 79%;
      min-height: 900px;
      float: left;

      .basicData {
        .operationBtn {
          //color: #3271f0;/**/
          //cursor: pointer;
          //margin-right: 10px;
        }
      }

      .pages {
        margin-top: 30px;
      }
    }
  }

  .treeBox:hover {
    font-weight: 600;
    color: #275cd4
  }

  .ivu-tree ul li {
    list-style: none;
    /* margin: 8px 0; */
    padding: 0;
    white-space: nowrap;
    outline: none;
  }

  .searchWrapper {
    background-color: #fff;
    height: 60px;
    line-height: 60px;
  }
}
</style>
